package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ApCollectionService;
import com.heima.article.service.ArticleConllectionService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.exception.CustomException;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApCollection;
import com.heima.model.behavior.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.common.protocol.types.Field;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class ArticleConllectionServiceImpl implements ArticleConllectionService {
    @Autowired
    private CacheService cacheService;

    @Autowired
    private ApCollectionService apCollectionService;

    @Autowired
    private ApArticleService apArticleService;

    /**
     * 处理用户收藏行为
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult handlerCollectionBehavior(CollectionBehaviorDto dto) {
        //1.入参校验
        if (dto == null || dto.getEntryId() == null || dto.getOperation() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询用户是否登录
        ApUser apUser = ApUserThreadLocalUtil.getUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApArticle article = apArticleService.getById(dto.getEntryId());
        if (article.getCollection() == null || article.getCollection() < 0) {
            article.setCollection(0);
        }
        //2.将数据存入到redis中, 根据键查询redis中是否存在(是否已经收藏,没有收藏数据则插入 ,同时插入数据表ap_collection
        String redisStr = (String) cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + apUser.getId(),
                dto.getEntryId().toString());
        if (StringUtils.isNoneBlank(redisStr) && dto.getOperation() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "用户已经收藏该文章!");
        }
        if (dto.getOperation() == 0) {
            //收藏
            cacheService.hPut(BehaviorConstants.COLLECTION_BEHAVIOR + apUser.getId(),
                    dto.getEntryId().toString(),
                    JSON.toJSONString(dto));

            //更新db
            ApCollection apCollection = ApCollection.builder()
                    .entryId(apUser.getId()) //实体id应该是为当前登录用户的id ?
                    .articleId(dto.getEntryId())
                    .type((short) 0)
                    .collectionTime(new Date())
                    .publishedTime(new Date())
                    .build();
            article.setCollection(article.getCollection() + 1);
            apArticleService.updateById(article);
            apCollectionService.save(apCollection);

        } else {
            //取消收藏 //3.如果是取消收藏,则删除redis中的数据同时删除数据表中的数据
            cacheService.hDelete(BehaviorConstants.COLLECTION_BEHAVIOR + apUser.getId(),
                    dto.getEntryId().toString());


            apCollectionService.remove(Wrappers.<ApCollection>lambdaQuery()
                    .eq(ApCollection::getArticleId, dto.getEntryId()));

            //更新db
            //更新ap_article表中的collection字段
            int temp = article.getCollection() - 1;
            if (temp < 0) {
                article.setCollection(0);
            } else {
                article.setCollection(article.getCollection() - 1);
            }
            apArticleService.updateById(article);


        }

        //4.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
